package com.supermarket.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.supermarket.dto.CategoryPageQueryDto;
import com.supermarket.entity.Category;
import com.supermarket.mapper.CategoryMapper;
import com.supermarket.service.CategoryService;
import com.supermarket.utils.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    @Override
    public PageResult list(CategoryPageQueryDto categoryPageQueryDto) {
        if (categoryPageQueryDto.getPage() == null) {
            categoryPageQueryDto.setPage(1);
        }
        if (categoryPageQueryDto.getPageSize() == null) {
            categoryPageQueryDto.setPageSize(10);
        }

        PageHelper.startPage(categoryPageQueryDto.getPage(), categoryPageQueryDto.getPageSize());
        Page<Category> page = categoryMapper.list(categoryPageQueryDto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Category getById(Long id) {
        return categoryMapper.getById(id);
    }

    @Override
    @Transactional
    public void save(Category category) {
        if (category.getStatus() == null) {
            category.setStatus(1);
        }
        categoryMapper.insert(category);
    }

    @Override
    @Transactional
    public void update(Category category) {
        categoryMapper.update(category);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        categoryMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void enableOrDisable(Integer status, Long id) {
        Category category = Category.builder()
                .id(id)
                .status(status)
                .build();
        categoryMapper.update(category);
    }

    @Override
    public List<Category> listAll() {
        CategoryPageQueryDto queryDto = new CategoryPageQueryDto();
        queryDto.setStatus(1); // 只查询启用的分类
        return categoryMapper.list(queryDto);
    }
} 